<?php

namespace app\common\model\hfztcy;

use app\common\model\BaseModel;
use common\Common;
use think\Db;
use think\Exception;
use think\Validate;

//公共函数

/**
 * 视频认证订单
 * @name LibOrderVipAuth.php
 * @package hfztcy
 * @category model
 * @link http://www.chanekeji.com
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2022-06-17
 */
class LibOrderVipAuth extends BaseModel
{
    protected $model;
    protected $table = 'hfztcy_order_vip_auth';

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = db($this->table);
        parent::__construct();
    }

    /**
     * 添加表单信息
     */
    public function addOrder($condition)
    {
        try {
            $result = $this->model->insertGetId($condition);
            if (true == $result) {
                return Common::errorArray(0, "添加成功", $result);
            } else {
                return Common::errorArray(1, "添加失败", $result);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }


    /**
     * 查询单个表单信息
     * @param $condition
     * @param array $result
     */
    public function findOrder($condition = '', $field = '')
    {
        try {
            $reslut = $this->model->where($condition)->field($field)->find();
            if (true == $reslut) {
                return Common::errorArray(0, "查询成功", $reslut);
            } else {
                return Common::errorArray(1, "查询为空", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 查询多个表单信息
     * @param $condition
     * @param $limit
     * @param $field
     * @param $sort
     * @param array $result
     */
    public function findAllOrder($condition = '', $limit = '', $field = '', $sort = 'add_time desc')
    {
        try {
            $reslut = $this->model->where($condition)->order($sort)->limit($limit)->field($field)->select();
            if (true == $reslut) {
                return Common::errorArray(0, "查询成功", $reslut);
            } else {
                return Common::errorArray(1, "查询为空", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 更新表单信息
     * @param $condition
     * @param $userInfo
     * @param array $result
     */
    public function updateOrder($condition, $userInfo)
    {
        try {
            $reslut = $this->model->where($condition)->update($userInfo);
            if ($reslut >= 0) {
                return Common::errorArray(0, "更新成功", $reslut);
            } else {
                return Common::errorArray(1, "更新失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 删除表单信息
     * @param $condition
     * @param array $result
     */
    public function deleteAllOrder($ids)
    {
        $condition = array('id' => array('in', $ids));
        try {
            $reslut = $this->model->where($condition)->delete();;
            if (true == $reslut) {
                return Common::errorArray(0, "删除成功", $reslut);
            } else {
                return Common::errorArray(1, "删除失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 删除表单信息
     * @param $condition
     * @param array $result
     */
    public function deleteOrder($ids)
    {
        $condition = array('id' => $ids);
        try {
            $reslut = $this->model->where($condition)->delete();;
            if (true == $reslut) {
                return Common::errorArray(0, "删除成功", $reslut);
            } else {
                return Common::errorArray(1, "删除失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 字段值加1
     * @param $condition
     * @param string $field
     * @param int $optval
     * @param array $reslut
     */
    public function increaseField($condition, $field, $optval = 1)
    {
        try {
            $reslut = $this->model->where($condition)->setInc($field, $optval);;
            if (true == $reslut) {
                return Common::errorArray(0, "修改成功", $reslut);
            } else {
                return Common::errorArray(1, "修改失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * 字段值减1
     * @param $condition
     * @param string $field
     * @param int $optval
     * @param array $reslut
     */
    public function decreaseField($condition, $field, $optval = 1)
    {
        try {
            $reslut = $this->model->where($condition)->setDec($field, $optval);;
            if (true == $reslut) {
                return Common::errorArray(0, "修改成功", $reslut);
            } else {
                return Common::errorArray(1, "修改失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败" . $ex->getMessage(), $ex);
        }
    }

    /**
     * Info: 订单列表
     * Date: 2022/11/2 14:13
     */
    public static function getOrderList ($args,$page)
    {
        $where = [];
        $where[] = "`type` = {$args['type']}";//订单类型
        $where[] = "`hide_order` = 0";
        if (!empty($args['username'])) $where[] = "`username` like '%" . $args['username'] . "%'";
        if (!empty($args['code'])) $where[] = "`code` like '%" . $args['code'] . "%'";
        if ($args['order_state'] != '') $where[] = "`state` = {$args['order_state']}";
        //if ($args['state'] != '') $where[] = "FIND_IN_SET({$args['state']},identity)";
        if (!empty($args['startTime'])) $where[] = "`a`.`add_time` >= '" . $args['startTime'] . "'";
        if (!empty($args['endTime'])) $where[] = "`a`.`add_time` <= '" . $args['endTime'] . ' 23:59:59' . "'";
        $result = self::getPagingOrderList($page, implode(' AND ', $where));
        $storeModel = new LibStore();
        $userVideoModel = new LibUserVideoAuth();
        foreach ($result['data']['dataList'] as &$item) {
            // 会员身份
            $memberIdentity = [
                '游客',
                '注册用户',
                'vip会员',
                '红娘',
                '门店'
            ];
            $identityIndex = [0,1,2,3,4];
            // 身份
            $identityList = explode(',',$item['identity']);
            $identityList = array_map('intval',$identityList);
            foreach ($memberIdentity as $k => $v) {
                if (!in_array($k,$identityList)) {
                    unset($memberIdentity[$k]);
                    unset($identityIndex[$k]);
                }
                if ($v == 'vip会员') {
                    if (isset($item['is_vip_overdue']) && $item['is_vip_overdue']) {
                        $memberIdentity[$k] = $v.'(过期)';
                    }
                }
                if ($v == '游客' && isset($item['audit_state']) && $item['audit_state'] == 0) {
                    $memberIdentity[$k] = $v.'(注册审核中)';
                }
            }
            $item['identity_text'] = implode(",",$memberIdentity);
            $item['identity_list'] = array_values($memberIdentity);
            $identityIndex = array_values($identityIndex);
            // 对于 hfztcy_user_video_auth 表状态， 0普通会员 1vip认证 2红娘认证 3门店认证
            if (count($identityIndex) > 1) {
                $identity_id = max($identityIndex);
                if ($identity_id == 3) $item['type'] = 2;
                if ($identity_id == 4) $item['type'] = 3;
            } else {
                if ($identityIndex[0] == 1) $item['type'] = 0;
                if ($identityIndex[0] == 2) $item['type'] = 1;
                if ($identityIndex[0] == 3) $item['type'] = 2;
                if ($identityIndex[0] == 4) $item['type'] = 3;
            }

            $item['store_info'] = [];
            $item['vcr_auth_info'] = null;
            $item['vcr_info'] = 0;
            if ($item['store_id']) {
                $store = $storeModel->findStore(['id' => $item['store_id']]);
                $item['store_info'] = $store['data'];

                $vcr = $userVideoModel->findUserVideoAuth(['order_id' => $item['id']]);
                $item['vcr_auth_info'] = $vcr['data'];
                $item['vcr_info'] = $vcr['errorCode'] == 0 ? 1 : 0;
            }

            $item['package_info'] && $item['package_info'] = json_decode($item['package_info'],true);
        }
        return $result;
    }

    /**
     * 分页获取数据表单信息
     */
    public function pagingOrder($page, $whereStr)
    {
        return self::getPagingOrderList($page, $whereStr);
    }

    private static function getPagingOrderList ($page, $whereStr)
    {
        $page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] ? $pageSize = $page['pageSize'] : $pageSize = 10;

        $m = ($pageIndex - 1) * $pageSize;
        $n = $pageSize;

        $where = 'id IS NOT NULL';
        if ($whereStr) {
            $where = "{$whereStr}";
        }

        $querySQL = <<< SQL
SELECT * 
FROM (
    SELECT b.*,
           a.amount,a.add_time,a.state,a.is_pick_up,a.order_id,a.package_id,a.package_info,a.is_offline,
           c.username,c.identity_id,
           d.identity
    FROM `hfztcy_order_vip_auth` `a` 
        LEFT JOIN `hfztcy_order` `b` ON `a`.`order_id`=`b`.`id` 
        LEFT JOIN `hfztcy_user` `c` ON `a`.`user_id`=`c`.`user_id` 
        LEFT JOIN `base_user` `d` ON `a`.`user_id`=`d`.`id` 
    where d.identity is not null and c.identity_id is not null
) AS a
WHERE {$where} 
ORDER BY a.add_time DESC 
SQL;


        $sql = $querySQL . " LIMIT {$m}, {$n}";
        //echo $sql;die();
        $sqlAll = $querySQL;

        $result['data']['dataList'] = Db::query($sql);
        $sql = "SELECT count(count_table.id) as total_record_num  from ( {$sqlAll} ) as count_table";

        $count = Db::query($sql);
        //如果之后1页，手动添加分页信息
        $result['data']['pageInfo']['current_page'] = $pageIndex;
        $result['data']['pageInfo']['first_page'] = 1;
        $result['data']['pageInfo']['prev_page'] = $pageIndex - 1;
        $result['data']['pageInfo']['next_page'] = $pageIndex + 1;
        $result['data']['pageInfo']['last_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['total_count'] = $count[0]['total_record_num'];
        $result['data']['pageInfo']['total_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['page_size'] = $pageSize;
        $result['data']['pageInfo']['all_pages'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['errorCode'] = 0;
        $result['errorInfo'] = '查询成功';

        return $result;
    }

    /**
     * Info: 订单号生成
     * Date: 2022/6/28 10:49
     */
    public function generateOrderNum()
    {
        $order_num = "ZTCY" . date("YmdHis") . rand(1000, 9999);
        $orderInfo = $this->findOrder(array('code' => $order_num));
        if ($orderInfo['errorCode'] == 0) {
            $this->generateOrderNum();
        } else {
            return $order_num;
        }
    }

    /**
     * Info: 数据验证
     * Date: 2022/6/17 9:55
     */
    public function goCheck($data, $opt = 'add')
    {
        $rule = [
            'user_id' => 'require',
            'amount' => 'require',
        ];

        $msg = [
            'user_id.require' => '用户不能为空',
            'amount.require' => '金额不能为空',
        ];

        $scene = [
            'add' => [
                'user_id',
                'amount',
            ],
            'edit' => [
                'user_id',
                'amount',
                'id'
            ],
        ];

        $validate = new Validate($rule, $msg);
        $validate->scene($opt, $scene[$opt]);
        if (!$validate->scene($opt)->check($data)) {
            return Common::errorArray(1, $validate->getError(), false);
        }
        return Common::errorArray(0, '验证通过', true);
    }
}

?>